package xusage.cumulus.log4j.listener;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.net.Socket;
import java.util.Hashtable;

import org.apache.log4j.Hierarchy;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.apache.log4j.spi.LoggingEvent;

public class CumulusLog4jServerNode implements Runnable {

	Socket socket;
	ObjectInputStream ois;
	Hashtable<String, Hierarchy> hashtable;

	public CumulusLog4jServerNode(Socket socket, Hashtable<String, Hierarchy> hashtable) {
		this.socket = socket;
		this.hashtable = hashtable;
		try {
			ois = new ObjectInputStream(new BufferedInputStream(socket.getInputStream()));
		}
		catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void run() {
		LoggingEvent event;
		Logger remoteLogger;
		try {
			if (ois != null) {
				while (true) {
					event = (LoggingEvent) ois.readObject();
					Object application = event.getMDC("application");
					if (application != null) {
						remoteLogger = LogManager.getLogger(application + "." + event.getLoggerName());
						if (remoteLogger != null && event.getLevel().isGreaterOrEqual(remoteLogger.getEffectiveLevel())) {
							remoteLogger.callAppenders(event);
						}
					}
				}
			}
		}
		catch (java.io.EOFException e) {
			LOGGER.error("End of socket stream : " + e.getMessage());
		}
		catch (java.net.SocketException e) {
			LOGGER.error("Socket Exception : " + e.getMessage());
		}
		catch (IOException e) {
			LOGGER.error("IO Exception : " + e.getMessage());
		}
		catch (Exception e) {
			e.printStackTrace();
		}
		finally {
			if (ois != null) {
				try {
					ois.close();
				}
				catch (Exception e) {
					e.printStackTrace();
				}
			}
			if (socket != null) {
				try {
					socket.close();
				}
				catch (IOException ex) {
					ex.printStackTrace();
				}
			}
		}
	}
	
	private static final Logger LOGGER = Logger.getLogger(CumulusLog4jServerNode.class);
}
